package com.tianyadu.security.core.social.qq.connet;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * @FileName: QQOAuth2Template
 * @Description: 自定义QQOAuth2Template
 * @author: xueyj
 * @create: 2018-12-14 19:47
 */
@Slf4j
public class QQOAuth2Template extends OAuth2Template {

    public QQOAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, accessTokenUrl);
        //  将useParametersForClientAuthentication设置为true，传递参数client_id，client_secret
        setUseParametersForClientAuthentication(true);
    }

    /** (non-Javadoc)
     * 处理QQ授权返回字符串信息
     * @see org.springframework.social.oauth2.OAuth2Template#postForAccessGrant(java.lang.String, org.springframework.util.MultiValueMap)
     */
    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {
        String responseStr = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);

        log.info("获取accessToke的响应：{}", responseStr);
        //  将QQ授权回调信息以&切割
        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(responseStr, "&");

        //  授权token
        String accessToken = StringUtils.substringAfterLast(items[0], "=");
        //  授权token有效时间
        Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
        //  刷新授权token
        String refreshToken = StringUtils.substringAfterLast(items[2], "=");

        //  自定义QQ授权信息
        return new AccessGrant(accessToken, null, refreshToken, expiresIn);
    }

    /** (non-Javadoc) 新增处理text/html格式RestTemplate处理
     * @see org.springframework.social.oauth2.OAuth2Template#createRestTemplate()
     */
    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = super.createRestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

}